const App=getApp()
Page({
  data:{
    isLogin:false
  },

  onShow(){
    const token=App.WechatService.getStorageSync("token")
    this.setData({
      isLogin:!!token
    })
  },
  //跳转至主页
  goIndex(){
    App.WechatService.redirectTo('/pages/index/index')
  },
  //用户注册
  userRegister(userInfo){
    App.HttpService.userRegister(userInfo)
    .then(res=>{
      this.token(userInfo.openId)
    })
  },

  //用户登录
  token(openId){
    App.HttpService.token({
      grant_type:'client_credentials',
      client_type:'wechatOpen',
      client_id:openId,
      client_secret:'carter'
    }).then(res=>{
      App.WechatService.setStorageSync('token',res.access_token)
      this.goIndex()
    })
  },

  //用户登录按钮点击事件
  onUserLogin(e){
    //调用登录接口，获取用户状态
    App.WechatService.login()
    .then(res=>{

      return App.HttpService.userStatus({
        code:res.code
      })
    })
    .then(res=>{
      if(res.data.isRegister){
        this.token(res.data.openId)
      }else{

        let userInfo=e.detail.userInfo
        userInfo.openId=res.data.openId
        this.userRegister(userInfo)
      }
    })
  }  
})